import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import {Button, Card, Icon, notification, Table} from 'antd';
import {Column} from '@ant-design/charts';
import {query} from "./actions";
import FilterForm from "../../components/FilterForm";
import {DATE_FORMAT} from "../../lib/func";
import {tableProps} from "../../lib/ui";
import moment from "moment";
import {getLastFilter, saveLastFilter} from "../../lib/identity";

const LAST_FILTER = "cargoAnalysis";

class CargoAnalysis extends PureComponent {
    componentDidMount() {
        const {dispatch} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({...fields}));
    }

    state = {
        createTimeRange: [moment().startOf('month'), moment().endOf('month')],
        createTimeStart: undefined,
        createTimeEnd: undefined
    };
    handleSearch = (values) => {
        const {dispatch} = this.props;
        let fields = values;
        this.setState({...values});
        if (fields.createTimeRange && fields.createTimeRange.length > 1) {
            fields.createTimeStart = fields.createTimeRange[0].format(DATE_FORMAT);
            fields.createTimeEnd = fields.createTimeRange[1].format(DATE_FORMAT);
            this.setState({createTimeStart: fields.createTimeStart, createTimeEnd: fields.createTimeEnd});
        }
        saveLastFilter(LAST_FILTER, {...values});
        dispatch(query({...values}));
    };

    createNewData = data => {
        return data.reduce((result, item) => {
            //首先将clientName字段作为新数组result取出
            if (result.indexOf(item.clientName) < 0) {
                result.push(item.clientName)
            }
            return result
        }, []).reduce((result, clientName) => {
            //将name相同的数据作为新数组取出，并在其内部添加新字段**rowSpan**
            const children = data.filter(item => item.clientName === clientName);
            result = result.concat(
                children.map((item, index) => ({
                    ...item,
                    rowSpan: index === 0 ? children.length : 0,//将第一行数据添加rowSpan字段
                }))
            )
            return result;
        }, [])
    };

    handleExport = () => {
        document.getElementById("exportCargo").submit();
        notification.success({
            message: '请等待文件导出'
        });
    };

    render() {
        const {
            cargoData
        } = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        //柱状图
        const businessData = [];
        cargoData.forEach(item => {
            const goodsName = item.goodsName;
            const goodsWeight = item.goodsWeight;
            const found = businessData.find(data => data.goodsName === goodsName);
            if (found) {
                found.goodsWeight = parseFloat((parseFloat(found.goodsWeight) + parseFloat(goodsWeight)).toFixed(3));
            } else {
                businessData.push({
                    goodsName, goodsWeight
                });
            }
        });
        console.info(businessData);
        const businessDataConfig = {
            title: {
                visible: true,
                text: '基础柱状图-图形标签位置',
            },
            forceFit: true,
            data: businessData,
            padding: 'auto',
            xField: 'goodsName',
            yField: 'goodsWeight',
            meta: {
                goodsName: {alias: '货物品类'},
                goodsWeight: {alias: '货物总重量(KG)'},
            },
            label: {
                visible: true,
                position: 'middle',
            }
        };
        const filterSchema = [
            {
                key: 'createTimeRange',
                field: 'createTimeRange',
                type: 'dateRangePicker',
                expandable: true,
                title: '发车日期',
                fieldOptions: {
                    initialValue: this.state.createTimeRange || fields.createTimeRange
                }
            }
        ];

        const columns = [
            {
                title: "客户",
                dataIndex: "clientName",
                width: "180px",
                render: (text, record) => {
                    return {
                        children: record.clientName,
                        props: {
                            rowSpan: record.rowSpan,
                        }
                    }
                }
            }, {
                title: "货物品类",
                dataIndex: "goodsName",
                width: "180px",
            }, {
                title: "货物重量总和(KG)",
                dataIndex: "goodsWeight",
                render: text => <span>{text && Number(text).toFixed(3)}</span>,
                width: "180px",
            }, {
                title: "",
                dataIndex: ""
            }
        ];

        return (
            <div>
                <FilterForm schema={filterSchema} callback={this.handleSearch}/>
                <Button onClick={this.handleExport}><Icon type="export"/>导 出</Button>
                <div style={{padding: '10px'}}>
                    <Card title={"货物品类分析柱状图"} bordered={false} style={{height: "500px", width: "100%"}}>
                        <Column {...businessDataConfig} />
                    </Card>
                </div>
                <Card>
                    <Table
                        {...tableProps}
                        columns={columns}
                        dataSource={this.createNewData(cargoData)}
                        pagination={false}
                    />
                </Card>
                <form
                    id="exportCargo"
                    method="post"
                    target="_blank"
                    action="/api/orderAnalysis/cargoExport"
                >
                    <input
                        name="createDateStart"
                        type="hidden"
                        value={this.state.createDateStart}
                    />
                    <input
                        name="createDateEnd"
                        type="hidden"
                        value={this.state.createDateEnd}
                    />
                </form>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.cargoAnalysis
    };
};

export default connect(mapStateToProps)(CargoAnalysis);
